<?php

declare(strict_types=1);

namespace app\common\model;

use think\Model;
use think\response\Json;

/**
 * @mixin \think\Model
 */
class DistrictPro extends Base
{

    protected $name = 'district_pro';

    public function pro()
    {
        return $this->hasOne(Pro::class, 'id', 'pro_id')->field('id,title');
    }
    public function district()
    {
        return $this->hasOne(District::class, 'id', 'district_id')->field('id,title');
    }

    //添加地区绑定所有数据
    public static function districtAll($district_id)
    {
        parent::startTrans();
        try {
            $prolist = Pro::where(['is_del' => 0])->column('id');
            $addAll = [];
            $district_pro = parent::where(['district_id' => $district_id, 'is_del' => 0])->column('pro_id');
            $sort = 1;
            foreach ($prolist as $k => $v) {
                if (!in_array($v, $district_pro) || empty($district_pro)) {
                    $dataadd['district_id'] = $district_id;
                    $dataadd['pro_id'] = $v;
                    $dataadd['create_time'] = time();
                    $dataadd['sort'] = $sort;
                    $sort += 1;
                    $addAll[] = $dataadd;
                }
            }
            if (!empty($addAll)) {
                parent::insertAll($addAll);
            }
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
